<template>
  <div class="historyTable">
    <div class="historyTable-toolbar">
      <div class="menu-wrapper">
        <el-menu mode="horizontal" defaultActive="1" class="dg-view-menu">
          <el-menu-item index="1">
            <el-icon>
              <platform />
            </el-icon>
            JJG
            {{props.lineCode == "JJGPDLine1" ? $t("wms.historicalData")
                :(props.lineCode == 'JJGPDLine2'?$t("wms.historicalData2"):$t("wms.historicalData3"))}}
          </el-menu-item>
        </el-menu>
        <div class="menu-right">
          <el-form :inline="true" label-width="100px">
            <el-form-item :label="$t('wms.classes')">
              <el-select v-model="data.classes" class="m-2 classes-select" :placeholder="$t('wms.select')" @change="change">
                <el-option v-for="item in data.options" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('wms.date')">
              <el-date-picker v-model="data.period" type="daterange" :range-separator="$t('wms.to')"
                :start-placeholder="$t('wms.startDate')" :end-placeholder="$t('wms.endDate')" format="YYYY-MM-DD"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">
                <el-icon>
                  <search />
                </el-icon>
                {{ $t("wms.search") }}
              </el-button>
              <el-button type="info" @click="onRest">
                <el-icon>
                  <RefreshLeft />
                </el-icon>
                {{ $t("wms.rest") }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="historyTable-content">
      <!-- JKJ序历史数据 END -->
      <div class="first-table">
        <div class="table-wrapper">
          <el-table
            border :data="data.rankListJKJ" :fit="true" table-layout="fixed" header-align="center"
            stripe style="width: 100%; height: 100%"
            :header-cell-style="{
              color: '#000',
              textAlign: 'center',
              borderColor: ' #CCC',
              background: '#f9f9f9',
            }" :cell-style="{ textAlign: 'center' }">
            <el-table-column :label="$t('wms.jkjProcessHistory')">
              <!--              <el-table-column prop="standardConsume" :label="$t('wms.claspData')" width="90"/>-->
              <el-table-column
                prop="materialcode"
                :label="$t('wms.materialCode')"
              >
                <template #default="scope">
                  <el-popover trigger="hover" placement="top" width="200">
                    <el-descriptions class="margin-top" :column="1" border>
                      <el-descriptions-item>
                        <template #label>
                          <i class="el-icon-user"></i>
                          {{ $t("wms.materialSpce") }}
                        </template>
                        {{ scope.row.materialSpec }}
                      </el-descriptions-item>
                    </el-descriptions>
                    <template v-slot:reference>
                      <div class="name-wrapper">
                        <el-tag size="large" effect="plain"
                          >{{ scope.row.materialcode }}
                        </el-tag>
                      </div>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="materialname" :label="$t('wms.materialName')"/>
              <el-table-column prop="totalqty" :label="$t('wms.outputQuantity')" width="90">
                <template #default="scope">
                  <el-tag>{{ scope.row.totalqty}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" :label="$t('wms.unit')" width="60" >
                <template #default="scope">
                  <el-tag type="warning">{{ scope.row.unit}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="reportstatus" :label="$t('wms.reportingStatus')"/>
              <el-table-column prop="produceendtime" :label="$t('wms.outputTime')"/>
            </el-table-column>
          </el-table>
        </div>
        <div class="demo-pagination-block">
          <el-pagination :currentPage="data.currentPageJKJ" :page-size="data.pagesizeJKJ"
            :page-sizes="[20, 30, 50, 100]" :small="small" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next, jumper" :total="data.totalJKJ"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </div>
      <!-- JKJ序历史数据 END -->

      <!-- PE工序历史数据 -->
      <div class="two-table">
        <div class="table-wrapper">
          <el-table border :data="data.rankListPE" :fit="true" table-layout="fixed"
            header-align="center" stripe style="width: 100%; height: 100%"
            :header-cell-style="{
              color: '#000',
             textAlign: 'center',
              borderColor: ' #CCC',
              background: '#f9f9f9',
            }" :cell-style="{ textAlign: 'center' }">
            <el-table-column :label="$t('wms.peProcessHistory')">
              <!--              <el-table-column prop="standardConsume" :label="$t('wms.claspData')" width="90"/>-->
              <el-table-column prop="materialcode" :label="$t('wms.materialCode')">
                <template #default="scope">
                  <el-popover trigger="hover" placement="top" width="200">
                    <el-descriptions class="margin-top" :column="1" size="small" border>
                      <el-descriptions-item>
                        <template #label>
                          <i class="el-icon-user"></i>
                          {{ $t("wms.materialSpce") }}
                        </template>
                        {{ scope.row.materialSpec }}
                      </el-descriptions-item>
                    </el-descriptions>
                    <template v-slot:reference>
                      <div class="name-wrapper">
                        <el-tag size="large" effect="plain"
                          >{{ scope.row.materialcode }}
                        </el-tag>
                      </div>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="materialname" :label="$t('wms.materialName')"/>
              <el-table-column prop="totalqty" :label="$t('wms.outputQuantity')" width="90">
                <template #default="scope">
                  <el-tag>{{ scope.row.totalqty}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" :label="$t('wms.unit')" width="60" >
                <template #default="scope">
                  <el-tag type="warning">{{ scope.row.unit}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="reportstatus" :label="$t('wms.reportingStatus')"/>
              <el-table-column prop="produceendtime" :label="$t('wms.outputTime')"/>
            </el-table-column>
          </el-table>
        </div>
        <div class="demo-pagination-block">
          <el-pagination :currentPage="data.currentPagePE" :page-size="data.pagesizePE" :page-sizes="[20, 30, 50, 100]"
            :small="small" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="data.totalPE" @size-change="handleSizeChangePE" @current-change="handleCurrentChangePE"/>
        </div>
      </div>
      <!-- PE工序历史数据 END -->

      <!-- DR工序历史数据 -->
      <div class="three-table">
        <div class="table-wrapper">
          <el-table border :data="data.rankListDR" :fit="true" table-layout="fixed" header-align="center"
            stripe style="width: 100%; height: 100%"
            :header-cell-style="{
              color: '#000',
              textAlign: 'center',
              borderColor: ' #CCC',
              background: '#f9f9f9',
            }" :cell-style="{ textAlign: 'center' }">
            <el-table-column :label="$t('wms.drProcessHistory')">
              <!--              <el-table-column prop="standardConsume" :label="$t('wms.claspData')" width="90"/>-->
              <el-table-column prop="materialCode" :label="$t('wms.materialCode')">
                <template #default="scope">
                  <el-popover trigger="hover" placement="top" width="200">
                    <el-descriptions class="margin-top" :column="1" size="small" border>
                      <el-descriptions-item>
                        <template #label>
                          <i class="el-icon-user"></i>
                          {{ $t("wms.materialSpce") }}
                        </template>
                        {{ scope.row.materialSpec }}
                      </el-descriptions-item>
                    </el-descriptions>
                    <template v-slot:reference>
                      <div class="name-wrapper">
                        <el-tag size="large" effect="plain"
                          >{{ scope.row.materialcode }}
                        </el-tag>
                      </div>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column prop="materialname" :label="$t('wms.materialName')" v-if="false"/>
              <el-table-column prop="barcode" :label="$t('mes.trayNumber')" >
                <template #default="scope">
                  {{ scope.row.barcode || '--'}}
                </template>
              </el-table-column>
              <el-table-column prop="totalqty" :label="$t('wms.outputQuantity')" width="90">
                <template #default="scope">
                  <el-tag>{{ scope.row.totalqty}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="unit" :label="$t('wms.unit')" width="60" >
                <template #default="scope">
                  <el-tag type="warning">{{ scope.row.unit}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="reportstatus" :label="$t('wms.reportingStatus')"/>
              <el-table-column prop="produceendtime" :label="$t('wms.outputTime')"/>
            </el-table-column>
          </el-table>
        </div>
        <div class="demo-pagination-block">
          <el-pagination :currentPage="data.currentPageDR" :page-size="data.pagesizeDR" :page-sizes="[20, 30, 50, 100]" :small="small"
            :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="data.totalDR" @size-change="handleSizeChangeDR" @current-change="handleCurrentChangeDR"/>
        </div>
      </div>
      <!-- DR工序历史数据 END -->
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, defineProps, defineEmits } from "vue";
import iconFont from "@/components/IconFont/iconFont";
import {
  getJKJProcessHistoryData,
  getPEProcessHistoryData,
  getDRProcessHistoryData,
  paperDocumentInspector,
} from "@/api/mesApi";
import useI18n from "@/hooks/language";

const { t } = useI18n();

const props = defineProps({
  lineCode: { type: String },
  // classes: { type: String },
  period: { type: Array },
});

const small = ref(false);
const background = ref(false);
const disabled = ref(false);

const data = reactive({
  currentPageJKJ: 1, // 当前页
  currentPagePE: 1, // 当前页
  currentPageDR: 1, // 当前页
  pagesizeJKJ: 20, // 每页显示多少条
  pagesizePE: 20, // 每页显示多少条
  pagesizeDR: 20, // 每页显示多少条
  totalJKJ: 0, // 总的多少数据
  totalPE: 0, // 总的多少数据
  totalDR: 0, // 总的多少数据
  rankListJKJ: [],
  rankListPE: [],
  rankListDR: [],
  classes: "ALL", // 班次
  period: [], // 周期
  options: [
    // {
    //   value: 'MorningShift',
    //   label: t('wms.morningShift')
    // },
    // {
    //   value: 'MiddleShift',
    //   label: t('wms.middleShift')
    // },
    // {
    //   value: 'EveningShift',
    //   label: t('wms.eveningShift')
    // }
  ],
});

onMounted(() => {
  setdefaulDate();
  processHistoryData();
  processHistoryData2();
  processHistoryData3();
  paperDocument();
  setTime();
});
const setdefaulDate = () => {
  var starTime = new Date(((new Date().getTime() / 1000) ) * 1000).toString()
  var endTime = new Date()
  data.period.push(format(starTime))
  data.period.push(format(endTime))
  // console.log(data.period.toString())
};
// 定时执行
const setTime = () => {
  setInterval(async () => {
    await processHistoryData();
    await processHistoryData2();
    await processHistoryData3();
    await paperDocument();
  }, 6000);
};
// 获取班次
const paperDocument = () => {
  paperDocumentInspector({ code: "ShiftTime" }).then((res) => {
    data.options = [];
    data.options.push({
      value: "ALL",
      text: "ALL",
    });
    res.data.forEach((item, index) => {
      data.options.push({
        value: item.text,
        label: item.text,
      });
    });
  });
};

watch(
  () => [props.lineCode],
  () => {
    // console.log(props.lineCode)
    processHistoryData();
    processHistoryData2();
    processHistoryData3();
  }
);

// 下拉选择改变值
const change = (val) => {
  // console.log(val)
  data.classes = val;
};
// 历史数据JKJ
const processHistoryData = () => {
  getJKJProcessHistoryData({
    current: data.currentPageJKJ,
    size: data.pagesizeJKJ,
    mesProduceDate: data.period[0] || "",
    mesProduceDate1: data.period[1] || "",
    shiftCode: data.classes === "ALL" ? "ALL" : data.classes,
    productionLineCode: props.lineCode,
  }).then((res) => {
    data.rankListJKJ = res.data.records;
    data.totalJKJ = res.data.total;
  });
};
// PE
const processHistoryData2 = () => {
  getPEProcessHistoryData({
    current: data.currentPageJKJ,
    size: data.pagesizeJKJ,
    mesProduceDate: data.period[0] || "",
    mesProduceDate1: data.period[1] || "",
    shiftCode: data.classes === "ALL" ? "ALL" : data.classes,
    productionLineCode: props.lineCode,
  }).then((res) => {
    data.rankListPE = res.data.records;
    data.totalPE = res.data.total;
  });
};
// DR
const processHistoryData3 = () => {
  getDRProcessHistoryData({
    current: data.currentPageJKJ,
    size: data.pagesizeJKJ,
    mesProduceDate: data.period[0] || "",
    mesProduceDate1: data.period[1] || "",
    shiftCode: data.classes === "ALL" ? "ALL" : data.classes,
    productionLineCode: props.lineCode,
  }).then((res) => {
    // console.log(res)
    data.rankListDR = res.data.records;
    data.totalDR = res.data.total;
  });
};
const format = (time) => {
  const date = new Date(time);
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份是从0开始的
  const day = date.getDate();
  const newTime =
    year +
    "-" +
    (month < 10 ? "0" + month : month) +
    "-" +
    (day < 10 ? "0" + day : day);

  return newTime;
};

const handleSizeChange = (val) => {
  data.pagesizeJKJ = val;
  processHistoryData();
};
const handleCurrentChange = (val) => {
  data.currentPageJKJ = val;
  processHistoryData();
};
//  PE表格分页
const handleSizeChangePE = (val) => {
  data.pagesizePE = val;
  processHistoryData2();
};
const handleCurrentChangePE = (val) => {
  data.currentPagePE = val;
  processHistoryData2();
};
//  DR表格分页
const handleSizeChangeDR = (val) => {
  data.pagesizeDR = val;
  processHistoryData3();
};
const handleCurrentChangeDR = (val) => {
  data.currentPageDR = val;
  processHistoryData3();
};
// 给父组件传递值
const emits = defineEmits(["getChildren"]);
const getYMD = (date) => {
  // 获取年份
  const year = date.getFullYear();
  // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
  const month = String(date.getMonth() + 1).padStart(2, "0");
  // 获取日期
  const day = String(date.getDate()).padStart(2, "0");
  // 拼接成 yyyy-MM-dd 格式的字符串
  const formattedDate = `${year}-${month}-${day}`;
  return formattedDate;
};
// 查询
const onSubmit = () => {
  if (data.period[0] !== undefined && data.period[0].length === undefined) {
    data.period[0] = getYMD(data.period[0]);
    data.period[1] = getYMD(data.period[1]);
  }
  // 传值父组件
  // console.log(data.period, data.classes)
  emits("getChildren", data.period, data.classes);
  processHistoryData();
  processHistoryData2();
  processHistoryData3();
};

const onRest = () => {
  data.period = [];
  data.classes = "";
  processHistoryData();
  processHistoryData2();
  processHistoryData3();
};
</script>

<style scoped lang="scss">
.historyTable {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  box-sizing: border-box;
  background-color: #fff;

  &-toolbar {
    height: 50px;

    .menu-wrapper {
      position: relative;
      display: flex;

      .dg-view-menu {
        width: 100%;
        padding-left: 20px;

        .el-menu-item {
          height: 50px;
          line-height: 50px;
          margin: 0 20px;
        }
      }

      .menu-right {
        position: absolute;
        top: 10px;
        right: 20px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  &-content {
    flex: 1 1 auto;
    overflow: hidden;
    display: flex;
    flex-direction: row;

    .first-table,
    .three-table {
      width: 33%;
      height: 100%;
      overflow: hidden;
    }

    .first-table,
    .two-table,
    .three-table {
      position: relative;

      .table-wrapper {
        width: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom: 40px;
      }

      .demo-pagination-block {
        position: absolute;
        left: 0;
        bottom: 0;
      }
    }

    .two-table {
      width: 34%;
      height: 100%;
      overflow: hidden;
    }
  }
}
</style>
